<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Strings in Python</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, strings, language, programming, learn Python">
<meta name="description" content="In this part of the Python tutorial, we will
work with strings.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Strings in Python</h1>

<p>
In this part of the Python programming tutorial, we will work with string 
data in more detail.  
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
Strings are one of the most important data types in computer languages. 
That is why we dedicate a whole chapter to working with strings in Python. 
</p>

<p>
Strings are derived data types. A string in Python is a sequence of characters.
Strings are immutable. This means that once defined, they cannot
be changed. Many Python methods modify strings. For example the <code>replace()</code>
method. They do not modify the original string. They create a copy of a string, which
they modify and return to the caller. 
</p>


<h2>String literals</h2>

<p>
In Python programming language, strings can be created with single quotes, 
double quotes or tripple quotes.
</p>


<p>
Strings in Python can be created using single quotes, double quotes and 
tripple quotes. When we use tripple quotes, strings can span several lines 
without using the escape character. 
</p>

<pre class="code">
#!/usr/bin/python

# strings.py

a = "proximity alert"
b = 'evacuation'
c = """
requiem 
for
a 
tower
"""

print a
print b
print c
</pre>

<p>
In our example we assign three string literals to a, b, c variables. And we 
print them to the console. 
</p>

<pre>
$ ./strings.py 
proximity alert
evacuation

requiem 
for 
a 
tower
</pre>

<p>
If we want to create unicode strings, we add a u/U character at the beginning of the text.
</p>

<pre class="code">
#!/usr/bin/python

# unicode.py

text = u'\u041b\u0435\u0432 \u041d\u0438\u043a\u043e\u043b\u0430\
\u0435\u0432\u0438\u0447 \u0422\u043e\u043b\u0441\u0442\u043e\u0439: \n\
\u0410\u043d\u043d\u0430 \u041a\u0430\u0440\u0435\u043d\u0438\u043d\u0430'

print text
</pre>

<p>
In our example, we print Leo Tolstoy: Anna Karenina in azbuka. 
</p>

<pre>
$ ./unicode.py 
Лев Николаевич Толстой: 
Анна Каренина
</pre>


<h2>Using quotes</h2>

<p>
Strings in Python are delimited by single or double quote characters.
What if we wanted to display quotes, for example in a direct speech? 
There are two basic ways to do this.
</p>

<pre class="code">
#!/usr/bin/python

# quotes.py

print "There are many stars." 
print "He said, \"Which one is your favourite?\""

print 'There are many stars.'
print 'He said, "Which one is your favourite?"'
</pre>

<p>
We use the (\) character to escape additional quotes. Normally the double 
quote character is used to delimit a string literal. However, when escaped, the 
original meaning is supressed. It appears as a normal character and can be 
used withing a string literal. The second way to use quotes within quotes is 
to mix single and double quotes.
</p>


<pre>
$ ./quotes.py
There are many stars.
He said, "Which one is your favourite?"
There are many stars.
He said, "Which one is your favourite?"
</pre>

<p>
Output.
</p>


<h2>The length of a string</h2>

<p>
The <code>len()</code> method calculates the number of characters
in a string. The white characters are also counted. 
</p>

<pre class="code">
#!/usr/bin/python

# length.py

s1 = "Eagle"
s2 = "Eagle\n"
s3 = "Eagle  "

print len(s1)
print len(s2)
print len(s3)
</pre>

<p>
We compute the length of three strings. 
</p>

<pre class="explanation">
s1 = "Eagle"
s2 = "Eagle\n"
s3 = "Eagle  "
</pre>

<p>
Three strings are defined. The second string has a new line character at
its end. The third has two space characters.
</p>

<pre class="explanation">
print len(s1)
</pre>

<p>
We print the number of characters to the console. 
</p>

<pre>
$ ./length.py
5
6
7
</pre>

<p>
From the output we can see, that the white spaces (new line character and space 
characters in our case) are counted too. 
</p>


<h2>Stripping white characters</h2>

<p>
In string processing, we might often end up with a string that
has white characters at the beginning or at the end of a string. 
The term white spaces, characters refers to invisible characters
like new line, tab, space or other control characters. We have
the <code>strip()</code>, <code>lstrip()</code> and <code>rstrip()</code>
methods to remove these characters. 
</p>

<pre class="code">
#!/usr/bin/python

# strippig.py

s = " Eagle  "

s2 = s.rstrip()
s3 = s.lstrip()
s4 = s.strip()

print s, len(s)
print s2, len(s2)
print s3, len(s3)
print s4, len(s4)
</pre>

<p>
We apply the stripping methods on a string word which has
three white spaces. One space at the start and two spaces 
at the end. Note that these methods remove any number of
white spaces, not just one.
</p>

<pre class="explanation">
s2 = s.rstrip()
</pre>

<p>
The <code>rstrip()</code> method returns a string with the trailing 
white space characters removed. 
</p>

<pre class="explanation">
s3 = s.lstrip()
</pre>

<p>
The <code>lstrip()</code> method returns a string with the leading 
white space characters removed. 
</p>

<pre class="explanation">
s4 = s.strip()
</pre>

<p>
The <code>strip()</code> method returns a copy of the string with 
the leading and trailing characters removed. 
</p>

<pre>
$ ./stripping.py
 Eagle   8
 Eagle 6
Eagle   7
Eagle 5
</pre>

<p>
Output of the stripping.py example. Remember that when we print output 
to the terminal, one space character is added between the 
string and the number. This happens when we delimit output by a comma
character for the print keyword. 
</p>


<h2>Escape sequences</h2>

<p>
When we work with strings, we can use <b>escape sequences</b>. The escape 
sequences are special characters, that have a specific purpose, when used 
within a string. 
</p>

<pre>
print "   bbb\raaa" # prints aaabbb
</pre>

<p>
The carriage return \r is a control character for end of line 
return to beginning of line.
</p>

<pre class="code">
#!/usr/bin/python

# strophe.py

print "Incompatible, it don't matter though\n'cos someone's bound to hear my cry"
print "Speak out if you do\nYou're not easy to find"
</pre>

<p>

The new line is a control character, which begins a new line of text. 
</p>

<pre>
$ ./strophe.py 
Incompatible, it don't matter though
'cos someone's bound to hear my cry
Speak out if you do
You're not easy to find
</pre>

<p>
Next we examine the backspace control character. 
</p>

<pre>
print "Python\b\b\booo" # prints Pytooo
</pre>

<p>
The backspace control character \b moves the cursor one character back. In 
our case, we use three backspace characters
to delete three letters and replace them with three o characters. 
</p>

<pre>
print "Towering\tinferno" # prints Towering        inferno
</pre>

<p>
The horizontal tab puts a space between text. 
</p>

<pre>
"Johnie's dog"
'Johnie\'s dog'
</pre>

<p>
Single and double quotes can be nested. Or in case we use only single quotes, 
we can use the backslash to escape the
default meaning of a single quote. 
</p>

<p>
If we prepend an r to the string, we get a raw string. The escape sequences 
are not interpreted.
</p>


<pre class="code">
#!/usr/bin/python

# raw.py

print r"Another world\n"
</pre>

<pre>
$ ./raw.py 
Another world\n
</pre>

<p>
We get the string with the lew line character included. 
</p>


<h2>Comparing strings</h2>

<p>
Comparing strings is a common job in programming. We can compare two strings 
with a == operator. We can check the opposite with the non-equality != operator.
The operators return a boolean True or False.
</p>

<pre class="code">
#!/usr/bin/python

print "12" == "12"
print "17" == "9"
print "aa" == "ab"

print "abc" != "bce"
print "efg" != "efg"
</pre>

<p>
In this code example, we compare some strings.
</p>

<pre class="explanation">
print "12" == "12"
</pre>

<p>
These two strings are equal, so the line returns True.
</p>

<pre class="explanation">
print "aa" == "ab"
</pre>

<p>
The first two characters of both strings are equal. Next the following characters 
are compared. They are different so the line returns False.
</p>

<pre class="explanation">
print "abc" != "bce"
</pre>

<p>
Since the two strings are different, the line returns True.
</p>

<pre>
$ ./comparing.py
True
False
False
True
False
</pre>

<p>
Output.
</p>


<h2>Accessing string elements</h2>

<p>
It is possible to access string elements in Python. 
</p>

<pre class="code">
#!/usr/bin/python

# elements.py

s = "Eagle"

print s[0]
print s[4]
print s[-1]
print s[-2]

print "****************"

print s[0:4]
print s[1:3]
print s[:]
</pre>

<p>
An index operation is used to get elements of a string.
</p>

<pre class="explanation">
print s[0]
print s[4]
</pre>

<p>
The first line prints the first character. The second line prints
the fifth character. The indexes start from zero. 
</p>

<pre class="explanation">
print s[-1]
print s[-2]
</pre>

<p>
When the index is negative, we retrieve elements from the end of
the string. In this case, we print the last and last but one characters.
</p>

<pre class="explanation">
print s[0:4]
</pre>

<p>
Ranges of characters can be accessed too. This line prints
a range of characters starting from the first and ending with 
the fourth character. 
</p>

<pre class="explanation">
print s[:]
</pre>

<p>
This line prints all the characters from the string.
</p>

<pre>
$ ./elements.py
E
e
e
l
****************
Eagl
ag
Eagle
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
A for loop can be used to traverse all characters of a string.
</p>

<pre class="code">
#!/usr/bin/python

s = "ZetCode"

for i in s:
  print i,
</pre>

<p>
The script prints all the characters of a given string
to the console.
</p>

<pre class="explanation">
$ ./traverse.py
Z e t C o d e
</pre>

<p>
Output.
</p>


<h2>Finding substrings</h2>

<p>
The <code>find()</code>, <code>rfind()</code>, <code>index()</code> and <code>rindex()</code>
methods are used to find substrings in a string. They return the index of the first occurrence
of the substring. The <code>find()</code> and <code>index()</code> methods search from the 
beginning of the string. The <code>rfind()</code> and <code>rindex()</code> search backwards.
</p>

<p>
The difference between the find() and index() methods is that when the substring is not found,
the former returns -1. The latter raises a <code>ValueError</code> exception.
</p>

<pre>
find(str, beg=0, end=len(string))
rfind(str, beg=0, end=len(string))
index(str, beg=0, end=len(string))
rindex(str, beg=0, end=len(string))
</pre>

<p>
The str is the substring to be searched for. The beg parameter is the starting index, by 
default it is 0. The end parameter is the ending index. It is by default equal to the length 
of the string.
</p>

<pre class="code">
#!/usr/bin/python

a = "I saw a wolf in the forest. A lone wolf."

print a.find("wolf")
print a.find("wolf", 10, 20)
print a.find("wolf", 15)

print a.rfind("wolf")
</pre>

<p>
We have a simple sentence. We try to find the index of a substring in the sentence.
</p>

<pre class="explanation">
print a.find("wolf")
</pre>

<p>
Finds the first occurrence of the substring 'wolf' in the sentence. The line
prints 8.
</p>

<pre class="explanation">
print a.find("wolf", 10, 20)
</pre>

<p>
This line tries to find a 'wolf' substring. It starts from the 10th character
and searches for the next 20 characters. There is no such substring is this
range and therefore the line prints -1. As for not found.
</p>

<pre class="explanation">
print a.find("wolf", 15)
</pre>

<p>
Here we search for a substring from the 15th character until the end of
the string. We find the second occurrence of the substring. The line
prints 35.
</p>

<pre class="explanation">
print a.rfind("wolf")
</pre>

<p>
The <code>rfind()</code> looks for a substring from the end. It finds the
second occurrence of the 'wolf' substring. The line prints 35.
</p>

<pre>
$ ./finding.py
8
-1
35
35
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
In the second example, we will use the <code>index()</code> method.
</p>

<pre class="code">
#!/usr/bin/python

a = "I saw a wolf in the forest. A lone wolf."

print a.index("wolf")
print a.rindex("wolf")

try:
    print a.rindex("fox")
except ValueError, e:
    print "Could not find substring"
</pre>

<p>
As we have already mentioned, the difference between these and the
previous ones is how they deal with not finding substrings.
</p>

<pre class="explanation">
print a.index("wolf")
print a.rindex("wolf")
</pre>

<p>
These lines find the first occurrence of the 'wolf' substring from the
beginning and from the end.
</p>

<pre class="explanation">
try:
    print a.rindex("fox")
except ValueError, e:
    print "Could not find substring"
</pre>

<p>
When the substring is not found, the <code>rindex()</code> method raises
a <code>ValueError</code> exception.
</p>

<pre>
$ ./finding2.py
8
35
Could not find substring
</pre>

<p>
Output.
</p>


<h2>Basic operations</h2>

<p>
In the next example, we will show string multiplication and concatenation. 
</p>

<pre class="code">
#!/usr/bin/python

# strings2.py

print "eagle " * 5

print "eagle " "falcon"

print "eagle " + "and " + "falcon"
</pre>

<p>
The * operation repeates the string n times. In our case five times. Two string 
literals next to each other are automatically concatenated. We can also use the + 
operator to explicitly concatenate the strings. 
</p>

<pre>
$ ./strings2.py 
eagle eagle eagle eagle eagle 
eagle falcon
eagle and falcon
</pre>

<p>
This is the output of the strings.py script. 
</p>

<p>
We can use the <code>len()</code> function to calculate the length 
of the string in characters. 
</p>

<pre class="code">
#!/usr/bin/python

# eagle.py

var = 'eagle'

print var, "has", len(var), "characters"
</pre>

<p>
In the example, we compute tht number of characters in a string variable.
</p>

<pre>
$ ./eagle.py 
eagle has 5 characters
</pre>

<p>
Some programming languages enable implicit addition of strings and numbers. 
In Python language, this is not possible. We must explicitly convert values. 
</p>

<pre class="code">
#!/usr/bin/python

# strnum.py

print int("12") + 12
print "There are " + str(22) + " oranges."
print float('22.33') + 22.55
</pre>

<p>
We use a built-in <code>int()</code> function to convert a string 
to integer. And there is also a built-in <code>str()</code> function 
to convert a number to a string. And we use the <code>float()</code> 
function to convert a string to a floating point number. 
</p>


<h2>Replacing strings</h2>

<p>
The <code>replace()</code> method replaces substrings in a string
with other substrings. Since strings in Python are immutable, a new
string is built with values replaced.
</p>

<pre>
replace(old, new [, max])
</pre>

<p>
By default, it replaces all occurrences of a substring. The method
takes a third argument which limits the replacements to a certain
number. 
</p>

<pre class="code">
#!/usr/bin/python

a = "I saw a wolf in the forest. A lonely wolf."

b = a.replace("wolf", "fox")
print b

c = a.replace("wolf", "fox", 1)
print c
</pre>

<p>
We have a sentence where we replace 'wolf' substring with a 'fox'
substring.
</p>

<pre class="explanation">
b = a.replace("wolf", "fox")
</pre>

<p>
This line replaces all occurrences of the 'wolf' substring with 
'fox' substring.
</p>

<pre class="explanation">
c = a.replace("wolf", "fox", 1)
</pre>

<p>
Here we replace only the first occurrence. 
</p>

<pre>
$ ./replacing.py
I saw a fox in the forest. A lonely fox.
I saw a fox in the forest. A lonely wolf.
</pre>

<p>
Output.
</p>


<h2>Splitting, joining strings</h2>

<p>
A string can be split with the <code>split()</code> or the 
<code>rsplit()</code> method. They return a list of strings which
were cut from the string using a separator. The optional second
parameter is the maximum splits allowed. 
</p>

<pre class="code">
#!/usr/bin/python

nums = "1,5,6,8,2,3,1,9"

k = nums.split(",")
print k

l = nums.split(",", 5)
print l

m = nums.rsplit(",", 3)
print m
</pre>

<p>
We have a comma-delimited string. We cut the string into parts. 
</p>

<pre class="explanation">
k = nums.split(",")
</pre>

<p>
We split the string into 8 parts using a comma as a separator. 
The method returns a list of 8 strings. 
</p>

<pre class="explanation">
l = nums.split(",", 5)
</pre>

<p>
Here we split the string into 6 parts. Five substrings split using the 
commna separator and the remainder of the string.
</p>

<pre class="explanation">
m = nums.rsplit(",", 3)
</pre>

<p>
Here we split the string into four parts. This time the splitting goes 
from the right.
</p>

<pre>
$ ./splitting.py
['1', '5', '6', '8', '2', '3', '1', '9']
['1', '5', '6', '8', '2', '3,1,9']
['1,5,6,8,2', '3', '1', '9']
</pre>

<hr class="btm">

<p>
Strings can be joined with the <code>join()</code> string. 
It returns a string concatenated from the strings passed as a parameter. 
The separator between elements is the string providing this method.
</p>

<pre class="code">
#!/usr/bin/python

nums = "1,5,6,8,2,3,1,9"

n = nums.split(",")
print n

m = ':'.join(n)
print m
</pre>

<p>
First we split a string into a list of strings. Then we
join the strings into one string with the elements being 
separated by the provided character.
</p>

<pre class="explanation">
m = ':'.join(n)
</pre>

<p>
The <code>join()</code> method creates one string from a list of
strings. The elements are separated by the : character. 
</p>

<pre>
$ ./splitjoin.py
['1', '5', '6', '8', '2', '3', '1', '9']
1:5:6:8:2:3:1:9
</pre>

<p>
Output.
</p>

<hr class="btm">

<p>
Another method which can be used for splitting strings is <code>partition()</code>. It will split the 
string at the first occurrence of the separator and return a 3-tuple containing the part before the 
separator, the separator itself, and the part after the separator. 
</p>

<pre class="code">
#!/usr/bin/python

s = "1 + 2 + 3 = 6"

a = s.partition("=")

print a
</pre>

<p>
We use the <code>partition()</code> method in this example.
</p>

<pre class="explanation">
a = s.partition("=")
</pre>

<p>
This will cut the string into three parts. One before the = character, the
separator and the right side after the separator. 
</p>

<pre>
$ ./partition.py
('1 + 2 + 3 ', '=', ' 6')
</pre>

<p>

</p>


<h2>Working with case</h2>

<p>
Python has four string methods to work with the case of the strings.
These methods return a new modified string. 
</p>

<pre class="code">
#!/usr/bin/python

# convert.py

a = "ZetCode"

print a.upper()
print a.lower()
print a.swapcase()
print a.title() 
</pre>

<p>
We have a string word on which we will demonstrate the four methods.
</p>

<pre class="explanation">
print a.upper()
</pre>

<p>
The <code>upper()</code> method returns a copy of the string where
all characters are converted to uppercase. 
</p>

<pre class="explanation">
print a.lower()
</pre>

<p>
Here we get a copy of the string in lowercase letters.
</p>


<pre class="explanation">
print a.swapcase()
</pre>

<p>
The <code>swapcase()</code> method swaps the case of the letters.
Lowercase characters will be uppercase and vice versa. 
</p>

<pre class="explanation">
print a.title() 
</pre>

<p>
The <code>title()</code> method returns a copy of the string, where
the first character is in uppercase and the remaining characters are
in lowercase. 
</p>

<pre>
$ ./convert.py
ZETCODE
zetcode
zETcODE
Zetcode
</pre>

<p>
Output.
</p>


<h2>Operations on strings</h2>

<p>
There are several useful built-in functions that can be used for working with string. 
</p>


<pre class="code">
#!/usr/bin/python

# letters.py

sentence = "There are 22 apples"

alphas = 0
digits = 0
spaces = 0

for i in sentence:
   if i.isalpha():
      alphas += 1
   if i.isdigit():
      digits += 1
   if i.isspace():
      spaces += 1

print "There are", len(sentence), "characters"
print "There are", alphas, "alphabetic characters"
print "There are", digits, "digits"
print "There are", spaces, "spaces"
</pre>

<p>
In our example, we have a string sentence. We calculate the absolute number 
of characters, number of alphabetic characters, digits and spaces in the 
sentence. To do this, we use functions: <code>len()</code>, 
<code>isalpha()</code>, <code>isdigit()</code> and 
<code>isspace()</code>.
</p>

<pre>
$ ./letters.py 
There are 19 characters
There are 14 alphabetic characters
There are 2 digits
There are 3 spaces
</pre>

<hr class="btm">

<p>
In the next example, we will print results of football matches.
</p>

<pre class="code">
#!/usr/bin/python

# teams.py

print "Ajax Amsterdam" " - " + "Inter Milano " "2:3"
print "Real Madridi" " - " "AC Milano " "3:3"
print "Dortmund" " - " "Sparta Praha " "2:1"
</pre>

<p>
We already know, that adjacent strings are concatenated. 
</p>

<pre>
$ ./teams1.py 
Ajax Amsterdam - Inter Milano 2:3
Real Madridi - AC Milano 3:3
Dortmund - Sparta Praha 2:1
</pre>

<p>
The output does not look very good. We will change it so that it looks better. 
</p>

<pre class="code">
#!/usr/bin/python

# teams.py

teams = { 
      0: ("Ajax Amsterdam", "Inter Milano"),
      1: ("Real Madrid", "AC Milano"),
      2: ("Dortmund", "Sparta Praha")
}

results = ("2:3", "3:3", "2:1")


for i in teams:
   print teams[i][0].ljust(16) + "-".ljust(5) + \
       teams[i][1].ljust(16) + results[i].ljust(3)
</pre>

<p>
The <code>ljust()</code> method returns a left justified string, 
the <code>rjust()</code> method returns a right justified string. 
If the string is smaller than the width that we provided, it is filled with spaces. 
</p>

<pre>
$ ./teams2.py 
Ajax Amsterdam  -    Inter Milano    2:3
Real Madrid     -    AC Milano       3:3
Dortmund        -    Sparta Praha    2:1
</pre>

<p>
Now the output looks better. 
</p>


<h2>String formatting</h2>

<p>
String formatting or string interpolation is dynamic putting of 
various values into a string. 
It is  a very handy feature of the Python programming language. 
To do string interpolation, we use the <b>%</b> operator. 
</p>

<pre class="code">
#!/usr/bin/python

# oranges.py

print 'There are %d oranges in the basket' % 32
</pre>

<p>
We use the %d formatting specifier. The d character says, we are expecting 
an integer. After the string, we put a modulo operator and an argument. In 
this case an integer value.  
</p>

<pre>
$ ./oranges.py 
There are 32 oranges in the basket
</pre>

<p>
If we interpolate more values, we put the arguments into a tuple. 
</p>

<pre class="code">
#!/usr/bin/python

# fruits.py

print 'There are %d oranges and %d apples in the basket' % (12, 23)
</pre>

<pre>
$ ./fruits.py 
There are 12 oranges and 23 apples in the basket
</pre>

<p>
In the next example, we will interpolate a float and a string value. 
</p>

<pre class="code">
#!/usr/bin/python

# height.py

print 'Height: %f %s' % (172.3, 'cm')
</pre>

<p>
The formatting specifier for a float value is <b>%f</b> and for a string <b>%s</b>.
</p>

<pre>
$ ./height.py 
Height: 172.300000 cm
</pre>

<p>
We might not like the fact, that the number in the previous example has 6 
decimal places by default. We can control the number of the decimal places 
in the formatting specifier. 
</p>

<pre class="code">
#!/usr/bin/python

# height2.py

print 'Height: %.1f %s' % (172.3, 'cm')
</pre>

<p>
The decimal point followed by an integer controls the number of decimal places. 
In our case, the number will have exactly one decimal place. 
</p>

<pre>
$ ./height2.py 
Height: 172.3 cm
</pre>

<p>
The following example shows other formatting options. 
</p>

<pre class="code">
#!/usr/bin/python

# various.py

# hexadecimal
print "%x" % 300
print "%#x" % 300

# octal
print "%o" % 300

# scientific
print "%e" % 300000
</pre>

<p>
The first two interpolations work with hexadecimal numbers. The <b>x</b> character 
will format the number in hexadecimal notation. The <b>#</b> character will add 0x 
to the hexadecimal number. The <b>o</b> character shows the number in 
octal format. The <b>e</b> character will show the number in scientific format. 
</p>

<pre>
$ ./various.py 
12c
0x12c
454
3.000000e+05
</pre>

<p>
The next example will print three columns of numbers. 
</p>

<pre class="code">
#!/usr/bin/python

# columns1.py

for x in range(1,11):
    print '%d %d %d' % (x, x*x, x*x*x)
</pre>

<p>
The numbers are left justified and the output looks terrible. 
</p>

<pre>
$ ./columns1.py 
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
</pre>

<p>
To correct this, we use the width specifier. The width specifier 
defines the minimal width of the object. If the 
object is smaller than the width, it is filled with spaces. 
</p>

<pre class="code">
#!/usr/bin/python

# spaces.py

for x in range(1,11):
    print '%2d %3d %4d' % (x, x*x, x*x*x)
</pre>

<p>
Now the output looks OK. 2 says that the first column will be 2 charactes wide. 
</p>

<pre>
$ ./columns2.py 
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
</pre>

<p>
This chapter was about string data type in Python. 
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 14, 2012  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

